package com.loanafter.fox.monitor.logback.connection;

import com.loanafter.fox.monitor.logback.event.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

/**
 * @author jasonli@kuainiugroup.com
 * @date 2020/7/30 下午5:15
 */
public abstract class AbstractConnection implements Connection {
    private static final Logger logger = LoggerFactory.getLogger(AbstractConnection.class);

    /**
     * Set of callbacks that will be called when an exception occurs while attempting to
     * send events to the Sentry server.
     */
    private Set<EventSendFailureCallback> eventSendFailureCallbacks;

    protected abstract void doSend(Event event) throws ConnectionException;

    @Override
    public final void send(Event event) throws ConnectionException {
        try {


            doSend(event);

        } catch (ConnectionException e) {
            for (EventSendFailureCallback eventSendFailureCallback : eventSendFailureCallbacks) {
                try {
                    eventSendFailureCallback.onFailure(event, e);
                } catch (Exception exc) {
                    logger.warn("An exception occurred while running an EventSendFailureCallback: "
                            + eventSendFailureCallback.getClass().getName(), exc);
                }
            }

            logger.warn("An exception due to the connection occurred, a lockdown will be initiated.", e);

            throw e;
        }
    }


    @Override
    public void addEventSendFailureCallback(EventSendFailureCallback eventSendFailureCallback) {
        eventSendFailureCallbacks.add(eventSendFailureCallback);
    }
}
